package com.example.redisdemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author wuyunbin
 */
@Service
public class DelayedDeleteService {

    @Autowired
    private  RedisTemplate redisTemplate;


  
    public void scheduleDelete(String key, long delayMillis) {
        // 在有序集合中添加元素，分数表示过期时间
        redisTemplate.opsForZSet().add("delayed_deletes", key, System.currentTimeMillis() + delayMillis);
    }

    public void performScheduledDeletes() {
        System.out.println("被调用了");
        long currentTimeMillis = System.currentTimeMillis();
        // 获取过期的元素（需要删除的键）
        redisTemplate.opsForZSet().rangeByScore("delayed_deletes", 0, currentTimeMillis).forEach(key -> {
            System.out.println("key:"+key);
            // 删除数据
            redisTemplate.delete(key);
            // 删除有序集合中的元素
            redisTemplate.opsForZSet().remove("delayed_deletes", key);
        });
    }
}
